// ------------------------- sync -----------------------------------

// const Koa = require('koa');
// const Router = require('koa-router');
// const json = require('koa-json');
// const serve = require('koa-static');
// const bodyParser = require('koa-bodyparser');

// const app = new Koa();
// const router = new Router();

// const todos = [];
// router
//   .get('/todos', ctx => {
//     ctx.body = todos;
//   })
//   .post('/todos', ctx => {
//     console.log('The post request is triggered...\n');
//     ctx.request.body.forEach(({ name }) => {
//       todos.push({ id: todos.length + 1, name });
//     });
//     ctx.body = todos;
//   });

// app.use(json());
// app.use(bodyParser());
// app.use(serve('./src'));
// app.use(router.routes());

// app.listen(8084, () => {
//   console.log('\nExample app running on http://127.0.0.1:8084\n');
// });

// ------------------------- sync -----------------------------------

// ------------------------- push notification ----------------------

const Koa = require('koa');
const Router = require('koa-router');
const json = require('koa-json');
const serve = require('koa-static');
const bodyParser = require('koa-bodyparser');

const webpush = require('web-push');

const app = new Koa();
const router = new Router();

webpush.setVapidDetails(
  'mailto:wsj230351@163.com',
  'BJwIJEHlX00w3wsVhDkKH3e_aC6wvAl3XKyILZzfM8zvRG-kZK8AtVBRaINPuIFAgjWlAs7jeZkaLgDpdhrQbWw',
  'LlyhtmjjdfX3FSrq1KD3RRLbkT8njFj-nbg_AcYTsSA'
);

let subscription = null;
const languages = ['C++', 'Java', 'JavaScript', 'Swift', 'Kotlin', 'Rust'];

function pushMessage(data) {
  // proxy 为翻墙代理 url 一般为 127.0.0.1:port - ClashX -> copy shell command 可查看到
  webpush.sendNotification(subscription, JSON.stringify(data), { proxy: 'http://127.0.0.1:7890' }).then(response => {
    console.log('\nThe data send successfully:', JSON.stringify(data));
  }).catch(err => {
    console.log('\nThe data send failed:', err);
  });
}

router
  .post('/push', ctx => {
    console.log('\nThe push request is triggered...');
    pushMessage({
      message: languages[Math.min(languages.length - 1, Math.floor(Math.random() * 10))],
      type: 'vote'
    });
    ctx.body = { status: true };
  })
  .post('/subscribe', ctx => {
    console.log('\nThe subscribe request is triggered...');
    subscription = ctx.request.body;
    pushMessage({
      message: '感谢订阅^ _ ^',
      type: 'subscribe'
    });
    ctx.body = { status: true };
  });

app.use(json());
app.use(bodyParser());
app.use(serve('./src'));
app.use(router.routes());

app.listen(8085, () => {
  console.log('\nExample app running on http://127.0.0.1:8085\n');
});

// ------------------------- push notification ----------------------
